<template>
  <div class="main">
    <div class="part">
      <div class="p-title">
        <div class="title">
          <span>风险总览</span>

          <MyToolTip
            content="本系统通过对用户多维度风险评估，利用数据模型为整个群体及单个用户进行风险画像，全方位评估及预测会员健康风险状况，为提升用户健康水平提供依托于大数据模型等数字化管理机制，同时也为未来与医保、商保在风险管控、人群健康管理 等业务场景中相应的运营管理奠定基础。"
          />
        </div>
        <div class="search">
          <myDestSelect @destChange="destChange" ref="destSelectRef" />
          <!-- <el-date-picker
            v-model="dateValue"
            type="daterange"
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
          /> -->
        </div>
      </div>
      <div class="p-cont p-cont-first">
        <div class="drug">
          <div class="title">
            <span>
              管理用户总数（人）
              <span>{{
                overviewData && formatNum(overviewData.member_cnt?.value)
              }}</span>
            </span>
            <MyToolTip
              content="指标定义：截止到筛选日期的一个自然年内，进入风险分析及控制的居民用户绝对人数。"
            />
          </div>
        </div>
        <div class="trend">
          <!-- <div class="title">趋势分析(人)</div> -->
          <div class="trend-content">
            <div class="tc-left">
              <div class="tc-btn">
                <div class="tc-title">
                  <span>会员分布</span>
                  <MyToolTip
                    content="指标定义：截止到筛选日期的一个自然年内，所有进入风控的用户按疾病和年龄的分布情况汇总"
                  />
                </div>
                <el-button
                  plain
                  :type="memberDataType === 'num' ? 'primary' : 'default'"
                  @click="changeMemberDataType"
                  >按年龄</el-button
                >
                <el-button
                  plain
                  :type="memberDataType === 'medical' ? 'primary' : 'default'"
                  @click="changeMemberDataType"
                  >按疾病</el-button
                >
              </div>

              <div class="tc-line" ref="memberDataRef" />
            </div>
            <div class="tc-right">
              <div class="tc-title">
                <span>平均合并症个数{{ avgComorbidityNum }}个</span>
                <MyToolTip
                  content="指标定义：截止到筛选日期的一个自然年内，所有进入风控的用户所患疾病的数量平均到每个风控用户的病症数量；该数字越小代表用户整体疾病种类越少，风险越可控。\n同时配套显示单个用户拥有病症数量的分布情况"
                />
              </div>
              <div class="trend-pie" ref="trendPieRef" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="part">
      <div class="section">
        <div class="title">
          现状分析
          <!-- <span>17126</span> -->
        </div>
        <div class="user-panel">
          <div
            :class="['up-item', selectedPanel.includes(1) ? 'active' : '']"
            @click="changeSelectedPanel(1)"
          >
            <div class="up-des">
              <span>总医疗支出 (元）</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，所有进入风控的用户的医疗总花费"
              />
            </div>
            <div class="up-num">
              {{ overviewData && formatNum(overviewData.total_cost?.value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="green"
                />
                <span class="green">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
          <div
            :class="['up-item', selectedPanel.includes(2) ? 'active' : '']"
            @click="changeSelectedPanel(2)"
          >
            <div class="up-des">
              <span>人均医疗支出 (元)</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，所有进入风控的用户的医疗平均花费"
              />
            </div>
            <div class="up-num">
              {{ overviewData && formatNum(overviewData.avg_cost?.value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="red"
                />
                <span class="red">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
          <div
            :class="['up-item', selectedPanel.includes(3) ? 'active' : '']"
            @click="changeSelectedPanel(3)"
          >
            <div class="up-des">
              <span>人均住院次数（次）</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，所有进入风控的用户平均的住院次数"
              />
            </div>
            <div class="up-num">
              {{ overviewData && formatNum(overviewData.ip_rate?.value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="red"
                />
                <span class="red">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
          <div
            :class="['up-item', selectedPanel.includes(4) ? 'active' : '']"
            @click="changeSelectedPanel(4)"
          >
            <div class="up-des">
              <span>人均处方量</span>
              <MyToolTip
                content="指标定义：截止到筛选日期的一个自然年内，所有进入风控的用户平均获取处方药处方的数量"
              />
            </div>
            <div class="up-num">
              {{ overviewData && formatNum(overviewData.avg_rx_cnt?.value) }}
            </div>
            <!-- <div class="up-inc">
              <div class="up-inc-left">
                <span>环比</span>
                <IconifyIconOnline
                  icon="material-symbols:arrow-circle-down-outline-rounded"
                  width="20px"
                  height="20px"
                  class="red"
                />
                <span class="red">12.5%</span>
              </div>
              <div class="up-inc-right">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div> -->
          </div>
        </div>
        <div class="chart chat-onechild">
          <div class="chart-title">
            <span>按用户疾病类型分布</span>
            <MyToolTip
              content="指标定义：与模块指标联动，显示对应指标按照会员所患的疾病分类汇总分布情况"
            />
          </div>
          <div class="now-analyse" ref="diseaseDistributeRef" />
        </div>
        <div class="chart">
          <div class="chart-left chart-item">
            <div class="chart-title">
              <span>趋势图</span>
              <MyToolTip
                content="指标定义：与模块指标联动，显示对应指标预期年化值和实际值的趋势曲线对比，本模块指标的实际值曲线比预期年化值小的，表示实际风控效果更好。"
              />
            </div>
            <!-- <div class="ch-btns">
              <el-button plain>按人数</el-button>
              <el-button plain type="primary">按医疗支出</el-button>
            </div> -->
            <div class="ch-chart" ref="diseaseTrendChartRef" />
          </div>
          <div class="chart-right chart-item">
            <div class="chart-title">
              <span>按金额分布</span>
              <MyToolTip
                content="指标定义：与模块指标联动，显示进入风控的用户在对应指标的人数分布情况"
              />
            </div>
            <!-- <div class="ch-btns">
              <el-button plain>按人数</el-button>
              <el-button plain type="primary">按医疗支出</el-button>
            </div> -->
            <div class="ch-chart" ref="diseaseMoneyChartRef" />
          </div>
        </div>
      </div>
    </div>
    <div class="part">
      <div class="section">
        <div class="title">
          <span>疾病进展 | 临床事件风险预测</span>
          <MyToolTip
            content="通过整合会员基础信息、疾病信息、就医信息、临床指标、家族病史、医疗支出、生活习惯、购药信息等，利用特征工程与预测模型，预测所有会员长期和短期的重大疾病风险，并按着风险程度进行排序，展示每个指标对应的会员平均值及分布情况。"
          />
          <!-- <span>17126</span> -->
        </div>
        <div class="user-table">
          <el-table
            :data="riskForecastData"
            style="width: 100%"
            :span-method="forecastSpanMethod"
          >
            <el-table-column prop="riskType" label="风险类型" width="180" />
            <el-table-column prop="risk_period" label="预测时长" />
            <el-table-column prop="risk" label="风险指标" />
            <el-table-column
              prop="member_cnt_complete"
              label="完整数据会员数"
              width="220"
            />
            <el-table-column
              prop="member_cnt_precent"
              label="完整数据会员占比"
              width="220"
            />
            <el-table-column prop="value" label="风险值（概率）" />
          </el-table>
        </div>
      </div>
    </div>
    <div class="part">
      <div class="section">
        <div class="section-header">
          <div class="title">
            <!-- <span>17126</span> -->
            <span>医疗支出风险预测</span>
            <MyToolTip
              content="通过界面选择所需要预测风险的时长（未来1年、未来3年及未来5年），经过医疗支出风险预测模型评估和测算，输出整体会员层面全部住院支出、重大疾病住院支出、以及恶性肿瘤发生率对应的具体预测金额及预测发生率。"
            />
          </div>
          <div class="btn">
            <el-button
              plain
              :type="medicalPayDataType === '1' ? 'primary' : 'default'"
              @click="changeMedicalPayDataType('1')"
              >未来1年</el-button
            >
            <el-button
              plain
              :type="medicalPayDataType === '3' ? 'primary' : 'default'"
              @click="changeMedicalPayDataType('3')"
              >未来3年</el-button
            >
            <el-button
              plain
              :type="medicalPayDataType === '5' ? 'primary' : 'default'"
              @click="changeMedicalPayDataType('5')"
              >未来5年</el-button
            >
          </div>
        </div>

        <div class="user-table">
          <el-table
            :data="medicalPayData"
            style="width: 100%"
            :span-method="medicalSpanMethod"
          >
            <el-table-column prop="riskType" label="风险类型" width="180" />
            <el-table-column prop="risk_period" label="预测时长" />
            <el-table-column prop="risk" label="风险指标" />
            <el-table-column
              prop="member_cnt_complete"
              label="完整数据会员数"
              width="220"
            />
            <el-table-column
              prop="member_cnt_precent"
              label="完整数据会员占比"
              width="220"
            />
            <el-table-column prop="value" label="风险值（概率）" />
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, ref, Ref, onUnmounted, reactive } from "vue";
import { ArrowRight } from "@element-plus/icons-vue";
import { useECharts } from "@pureadmin/utils";
import * as echartsTypes from "echarts/types/dist/echarts";
import type { TableColumnCtx } from "element-plus";
import { globalDataStoreHook } from "@/store/modules/globalData";
import MyToolTip from "@/components/myToolTip.vue";
import {
  getMemberDataByMedical,
  getMemberDataByNum,
  getRiskOverview,
  getComorbidityData,
  getPresentSituationByMedical,
  getPresentSituationByTrend,
  getPresentSituationByMoney,
  getGlobalLabelValueList,
  getRiskForecastData,
  getMedicalPayData
} from "@/api/health_risk";
import { formatNum } from "@/utils/tools";
import myDestSelect, { destSelectType } from "@/components/myDestSelect.vue";

const selectedPanel = ref([1]);

const destSelectRef = ref<destSelectType | null>(null);

interface RiskInt {
  riskType: string;
  time: string;
  quota: string;
  memberNum: string;
  precent: string;
  riskNum: string;
}

interface forecastSpanInt {
  row: RiskInt;
  column: TableColumnCtx<RiskInt>;
  rowIndex: number;
  columnIndex: number;
}

const memberDataRef = ref(null);
const trendPieRef = ref(null);
const diseaseDistributeRef = ref(null);
const diseaseTrendChartRef = ref(null);
const diseaseMoneyChartRef = ref(null);

const memberDataIns = ref(null);
const comorbidityPieIns = ref(null);
const diseaseDistributeIns = ref(null);
const diseaseTrendChartIns = ref(null);
const diseaseMoneyChartIns = ref(null);
// 平均合并症个数
const avgComorbidityNum = ref<number>(0);

const memberDataOption = reactive({
  title: {
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true
  },
  xAxis: {
    type: "category",
    data: [],
    axisLabel: {
      interval: 0
    }
  },
  yAxis: {
    type: "value"
  },
  label: {
    show: true,
    position: "top"
  },
  barWidth: "20",
  series: [
    {
      data: [],
      type: "bar"
    }
  ]
});

function initMemberData(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(memberDataOption as any);
  return getInstance();
}

const memberDataType = ref("num");

function changeMemberDataType() {
  let dataType = memberDataType.value;
  dataType = dataType === "num" ? "medical" : "num";
  memberDataType.value = dataType;
  setMemberData();
}

async function setMemberData() {
  if (memberDataType.value === "num") {
    const res = await getMemberDataByNum(
      destSelectRef.value.userSelectedRegions.cityId
    );
    memberDataOption.xAxis.data = res.list.map(item => {
      return item.label;
    });
    memberDataOption.series[0].data = res.list.map(item => {
      return item.value;
    });
  } else {
    const res = await getMemberDataByMedical(
      destSelectRef.value.userSelectedRegions.cityId
    );
    memberDataOption.xAxis.data = res.list.map(item => {
      return item.label;
    });
    memberDataOption.series[0].data = res.list.map(item => {
      return item.value;
    });
  }
  // console.log("memberDataOption:", memberDataOption);
  memberDataIns.value.setOption(memberDataOption);
}

const comorbidityOption = reactive({
  title: {
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    bottom: "5%",
    left: "center",
    show: true
  },
  series: [
    {
      name: "合并症个数",
      type: "pie",
      radius: ["40%", "70%"],
      avoidLabelOverlap: false,
      label: {
        show: true,
        position: "outside"
      },

      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: "bold"
        }
      },
      labelLine: {
        show: true
      },
      data: [
        { value: 1048, name: "Search Engine" },
        { value: 735, name: "Direct" },
        { value: 580, name: "Email" },
        { value: 484, name: "Union Ads" },
        { value: 300, name: "Video Ads" }
      ]
    }
  ]
});

function initComorbidityPie(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(comorbidityOption as any);
  return getInstance();
}

async function setComorbidityOption() {
  const res = await getComorbidityData(
    destSelectRef.value.userSelectedRegions.cityId
  );
  const totalNum = res.list.reduce((total, cur) => {
    return total + cur.value;
  }, 0);
  const comorbidityNum = res.list.reduce((total, cur) => {
    let labelNum = parseInt(cur.label);
    if (Number.isNaN(labelNum)) {
      labelNum = 4;
    }
    return total + cur.value * labelNum;
  }, 0);
  avgComorbidityNum.value = Number((comorbidityNum / totalNum).toFixed(1)) || 0;
  // comorbidityOption.title.text = `平均合并症个数：${(
  //   comorbidityNum / totalNum
  // ).toFixed(1)}个`;
  comorbidityOption.series[0].data = res.list.map(item => {
    return {
      value: item.value,
      name: item.label
    };
  });
  comorbidityPieIns.value.setOption(comorbidityOption);
}

const diseaseDistributeOption = reactive({
  title: {
    // text: "按用户疾病类型分布",
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  xAxis: {
    type: "category",
    data: [
      "高血压",
      "慢性缺血性心脏病",
      "糖尿病",
      "高脂血症",
      "脑梗死",
      "急性心肌梗死",
      "其他脑血管病"
    ],
    axisLabel: {
      interval: 0
    }
  },
  yAxis: {
    type: "value"
  },
  barWidth: "20",
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130],
      type: "bar",
      label: {
        show: true,
        formatter: "{c}%",
        position: "top"
      }
    }
  ]
});

function initDiseaseDistribute(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(diseaseDistributeOption as any);
  return getInstance();
}

async function setDiseaseDistributeData(panelType) {
  const res = await getPresentSituationByMedical(
    panelType,
    destSelectRef.value.userSelectedRegions.cityId
  );
  diseaseDistributeOption.xAxis.data = res.xaxis;
  diseaseDistributeOption.series[0].data = res.series.map(item => {
    return Math.floor(Number(item) * 100);
  });
  diseaseDistributeIns.value.setOption(diseaseDistributeOption);
}

const diseaseTrendOption = reactive({
  title: {
    // text: "趋势分析(人)",
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  legend: {
    data: ["实际值", "年化值"]
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true
  },

  xAxis: {
    type: "category",
    boundaryGap: false,
    data: ["2018", "2019", "2020"]
  },
  yAxis: {
    type: "value",
    axisLabel: {
      margin: 40
    }
  },
  label: {
    show: true
  },

  series: [
    {
      name: "实际值",
      type: "line",
      data: [120, 132, 101]
    },
    {
      name: "年化值",
      type: "line",
      data: [120, 132, 101]
    }
  ]
});

function initDiseaseTrendChart(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(diseaseTrendOption as any);
  return getInstance();
}

async function setDiseaseTrendData(panelType) {
  const res = await getPresentSituationByTrend(
    panelType,
    destSelectRef.value.userSelectedRegions.cityId
  );
  diseaseTrendOption.xAxis.data = res.xaxis;
  diseaseTrendOption.series[0].data = res.series.map(item => {
    return Number(item);
  });
  diseaseTrendOption.series[1].data = res.series2.map(item => {
    return Number(item);
  });
  // console.log("diseaseTrendOption:", diseaseTrendOption);
  diseaseTrendChartIns.value.setOption(diseaseTrendOption);
}

const diseaseMoneyOption = {
  title: {
    // text: "按金额分布",
    textStyle: {
      color: "#333",
      fontFamily: "PingFang SC",
      fontSize: "18px"
    }
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    containLabel: true
  },
  tooltip: {
    show: true,
    trigger: "axis"
  },
  xAxis: {
    type: "category",
    data: [
      "高血压",
      "慢性缺血性心脏病",
      "糖尿病",
      "高脂血症",
      "脑梗死",
      "急性心肌梗死",
      "其他脑血管病"
    ]
  },
  yAxis: {
    type: "value"
  },
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130],
      type: "bar",
      label: {
        show: true,
        position: "top"
      }
    }
  ],
  barWidth: "20"
};
function initDiseaseMoneyChart(elRef): echartsTypes.ECharts {
  const { setOptions, getInstance } = useECharts(elRef as Ref<HTMLDivElement>);
  setOptions(diseaseMoneyOption as any);
  return getInstance();
}

async function setDiseaseMoneyData(panelType) {
  const res = await getPresentSituationByMoney(
    panelType,
    destSelectRef.value.userSelectedRegions.cityId
  );
  diseaseMoneyOption.xAxis.data = res.xaxis;
  diseaseMoneyOption.series[0].data = res.series.map(item => {
    return Number(item);
  });
  diseaseMoneyChartIns.value.setOption(diseaseMoneyOption);
}

function forecastSpanMethod({ rowIndex, columnIndex }: forecastSpanInt) {
  if (columnIndex === 0) {
    if (rowIndex % 2 === 0) {
      return {
        rowspan: 2,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
}

function medicalSpanMethod({ row, rowIndex, columnIndex }: forecastSpanInt) {
  if (columnIndex === 0) {
    if (rowIndex === 0 || rowIndex === 2) {
      return {
        rowspan: 2,
        colspan: 1
      };
    } else if (rowIndex === 4) {
      return {
        rowspan: medicalPayData.value.filter(item => {
          return item.riskType === "恶性肿瘤发生率";
        }).length,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
}

function resizeChart() {
  // console.log("resizeChart");
  memberDataIns.value?.resize();
  comorbidityPieIns.value?.resize();
  diseaseDistributeIns.value?.resize();
  diseaseTrendChartIns.value?.resize();
  diseaseMoneyChartIns.value?.resize();
}

function getNameByLabel(label) {
  if (label) {
    const item = globalKeyValueList.value.find(item => {
      return item.label === label;
    });
    if (item) {
      return item.value;
    } else {
      return label;
    }
  }
  return label;
}

function convertOriginDataToTableData(item, riskType) {
  return {
    riskType,

    risk_period: getNameByLabel(item.risk_period),
    risk: getNameByLabel(item.risk),
    member_cnt_complete: item.member_cnt_complete,
    member_cnt_precent:
      ((item.member_cnt_complete / item.member_cnt) * 100).toFixed(2) + "%",
    value: item.value
  };
}
const riskForecastData = ref([]);
async function setRiskForecastData() {
  const riskRes = await getRiskForecastData(
    destSelectRef.value.userSelectedRegions.cityId
  );
  const originShortRiskData =
    riskRes.list.find(item => {
      return item.risk_type === "short_term";
    })?.data || [];
  const originLongRiskData =
    riskRes.list.find(item => {
      return item.risk_type === "long_term";
    })?.data || [];

  const shortRiskData = originShortRiskData.map(item => {
    return convertOriginDataToTableData(item, "短期风险指标");
  });
  const longRiskData = originLongRiskData.map(item => {
    return convertOriginDataToTableData(item, "长期风险指标");
  });
  riskForecastData.value = [...shortRiskData, ...longRiskData];
}

const medicalPayDataType = ref("1");
const medicalPayData = ref([]);

function changeMedicalPayDataType(value) {
  medicalPayDataType.value = value;
  setMedicalPayData(value + "yr");
}

async function setMedicalPayData(yearType) {
  const riskRes = await getMedicalPayData(
    destSelectRef.value.userSelectedRegions.cityId,
    yearType
  );
  const originTotalHospital =
    riskRes.list.find(item => {
      return item.risk_type === "ip_total";
    })?.data || [];

  const originComorbidityHospital =
    riskRes.list.find(item => {
      return item.risk_type === "ip_ci";
    })?.data || [];

  const originCancerHospital =
    riskRes.list.find(item => {
      return item.risk_type === "cancer";
    })?.data || [];

  const totalHospitalData = originTotalHospital.map(item => {
    return convertOriginDataToTableData(item, "全部住院");
  });
  const comorbidityHospitalData = originComorbidityHospital.map(item => {
    return convertOriginDataToTableData(item, "重大疾病住院");
  });
  const cancerHospitalData = originCancerHospital.map(item => {
    return convertOriginDataToTableData(item, "恶性肿瘤发生率");
  });
  medicalPayData.value = [
    ...totalHospitalData,
    ...comorbidityHospitalData,
    ...cancerHospitalData
  ];
}

const overviewData = ref(null);
// 中英文键值对
const globalKeyValueList = ref([]);

const panelTypeList = ["total_cost", "avg_cost", "ip_rate", "avg_rx_cnt"];

function changeSelectedPanel(val) {
  selectedPanel.value.splice(0, 1, val);

  setDiseaseDistributeData(panelTypeList[val]);
  setDiseaseTrendData(panelTypeList[val]);
  setDiseaseMoneyData(panelTypeList[val]);

  setTimeout(() => {
    initEchart();
  }, 0);
}

// 用于初始化数据
async function init() {
  globalKeyValueList.value = await getGlobalLabelValueList();
  overviewData.value = await getRiskOverview(
    destSelectRef.value.userSelectedRegions.cityId
  );
  // 临床事件风险预测总览
  setRiskForecastData();
  setMedicalPayData("1yr");
}
// 用于初始化echart图表
function initEchart() {
  setMemberData();
  setComorbidityOption();
  setDiseaseDistributeData(panelTypeList[0]);
  setDiseaseTrendData(panelTypeList[0]);
  setDiseaseMoneyData(panelTypeList[0]);
}
function destChange(cityObj) {
  // console.log("value:", value);

  globalDataStoreHook().CHANGE_CITY_ID(cityObj.cityId);
  init();
  initEchart();
}

onMounted(() => {
  init();
  memberDataIns.value = initMemberData(memberDataRef);
  comorbidityPieIns.value = initComorbidityPie(trendPieRef);
  diseaseDistributeIns.value = initDiseaseDistribute(diseaseDistributeRef);
  diseaseTrendChartIns.value = initDiseaseTrendChart(diseaseTrendChartRef);
  diseaseMoneyChartIns.value = initDiseaseMoneyChart(diseaseMoneyChartRef);

  initEchart();
  window.addEventListener("resize", resizeChart);
});
onUnmounted(() => {
  window.removeEventListener("resize", resizeChart);
});
</script>
<style scoped lang="scss">
.search {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .el-select {
    margin-right: 20px;
  }

  .el-date-picker {
    margin-left: 20px;
  }
}

.p-cont {
  background-color: white;
  border-radius: 4px;

  .drug {
    .title {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      display: flex;
      align-items: center;

      span {
        font-size: 24px;
      }
    }

    .user-panel {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20px;

      .up-item {
        border: 1px solid #eee;
        border-radius: 8px;
        width: 24%;
        padding: 20px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
        height: 130px;

        &.active {
          background-color: #4993fa;

          .up-des {
            color: white;
          }

          .up-num {
            color: white;
          }

          .up-inc {
            color: white;
          }
        }

        .up-des {
          @include panelSubTitle;
        }

        .up-num {
          @include panelBigTitle;
          margin-top: 10px;
        }

        .up-inc {
          @include panelThirdTitle;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 10px;

          .up-inc-left {
            display: flex;
            align-items: center;
            width: 110px;
            justify-content: space-between;

            .green {
              color: #00a870;
            }

            .red {
              color: #e54d59;
            }
          }

          .up-inc-right {
            cursor: pointer;
          }
        }
      }
    }
  }

  .trend {
    .trend-content {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .tc-single {
        width: 100%;
      }

      .tc-left {
        width: 50%;
      }

      .tc-btn {
        text-align: left;
        display: flex;
        justify-content: flex-end;
      }

      .tc-title {
        font-size: 18px;
        color: #333;
        font-weight: bold;
        display: flex;
        align-items: center;
        width: 100%;
      }

      .tc-line {
        width: 100%;
        height: 400px;
        margin-top: 20px;
      }

      .tc-right {
        width: calc(50% - 20px);
        box-sizing: border-box;
        padding-top: 55px;
        border-left: 1px solid #eee;
        margin-top: 20px;
        margin-left: 40px;
        padding-left: 40px;

        .trend-pie {
          height: 400px;
        }

        .tc-r-item {
          width: 100%;
          height: 200px;
          box-sizing: border-box;
          padding-left: 20px;

          .tc-r-title {
            font-size: 12px;
            color: #bbb;
          }

          .tc-r-num {
            font-size: 36px;
            color: black;
            margin-top: 20px;
          }

          .tc-r-inc {
            display: flex;
            align-items: center;
            margin-top: 20px;
          }
        }
      }
    }
  }
}

.section {
  .title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    display: flex;
    align-items: center;

    span {
      font-size: 24px;
    }
  }

  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;

    .title {
      display: flex;
      align-items: center;
    }
  }

  .user-table {
    margin-top: 20px;
  }

  .user-panel {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;

    .up-item {
      border: 1px solid #eee;
      border-radius: 8px;
      width: 24%;
      padding: 20px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      height: 130px;

      &.active {
        background-color: #4993fa;

        .up-des {
          color: white;
        }

        .up-num {
          color: white;
        }

        .up-inc {
          color: white;
        }
      }

      &.hidden {
        visibility: hidden;
      }

      .up-des {
        @include panelSubTitle;
      }

      .up-num {
        @include panelBigTitle;
        margin-top: 10px;
      }

      .up-inc {
        @include panelThirdTitle;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 10px;

        .up-inc-left {
          display: flex;
          align-items: center;
          width: 110px;
          justify-content: space-between;

          .green {
            color: #00a870;
          }

          .red {
            color: #e54d59;
          }
        }

        .up-inc-right {
          cursor: pointer;
        }
      }
    }
  }

  .chart {
    margin-top: 20px;
    margin-bottom: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    &.chat-onechild {
      display: block;
    }

    .chart-title {
      font-size: 18px;
      color: #333;
      font-weight: bold;
      display: flex;
      align-items: center;
    }

    .now-analyse {
      width: 100%;
      height: 400px;
    }

    .chart-item {
      width: calc(50% - 20px);

      .ch-btns {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 60px;
        margin-bottom: 20px;
      }

      &.chart-flex-col {
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: space-between;

        .ch-row {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 100px;
          width: 100%;

          .ch-col-label {
            width: 120px;
            text-align: center;
          }

          .ch-col-pie {
            width: 120px;
            height: 120px;
          }
        }

        .ch-list {
          width: 100%;
        }
      }

      .ch-chart {
        height: 300px;
      }

      .ch-list {
        height: 300px;

        .ch-t-index {
          width: 24px;
          height: 24px;
          border-radius: 20px;
          display: inline-block;
          background: #0052d9;
          color: white;
          text-align: center;
          line-height: 24px;
        }

        .ch-t-cont {
          display: flex;
          align-items: center;

          .ch-t-bar {
            width: 150px;
            height: 12px;
            border-radius: 20px;
            background: #eee;

            .ch-t-bar-inner {
              height: inherit;
              background: #0052d9;
              border-radius: 20px;
            }
          }

          .ch-t-num {
            margin-left: 5px;
          }
        }
      }
    }
  }
}

.part2 {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;

  .section {
    width: calc(50% - 20px);

    .user-panel {
      .up-item {
        width: 49%;

        &.active {
          background-color: #4993fa;

          .up-des {
            color: white;
          }

          .up-num {
            color: white;
          }

          .up-inc {
            color: white;
          }
        }
      }
    }

    .chart {
      // margin-left: 40px;
      .chart-item {
        width: 100%;
      }
    }
  }
}
</style>
